<template>
  <view>
    <u-form-item :required="item.required"  :key="item.key" :colorstyle="'white'" :flag="2">
      <!--            <u-upload :action="action"-->
      <!--                      :file-list="item.value"-->
      <!--                      :max-size="imageMaxSize"-->
      <!--                      :width="width"-->
      <!--                      :height="height"-->
      <!--                      :auto-upload="autoUpload"-->
      <!--                      :show-upload-list="showUploadList"-->
      <!--                      :del-bg-color="delBgColor"-->
      <!--                      :del-color="delColor"-->
      <!--                      :upload-text="uploadText"-->
      <!--                      :limit-type="limitType"-->
      <!--                      @on-success="onSuccess"-->
      <!--                      @on-remove="onRemove"-->
      <!--            >-->
      <!--            </u-upload>-->
      <view>
        <view class="filePreview">
          
		  <view class="item" v-if="false" v-for="(item, index) in showDataList" :key="index">
            <view class="text" v-if="item.name&&text!=$t('上传')">
               {{ item.name.substring(item.name.length, item.name.length - 20) }} 
            </view>
            <view class="text" v-else-if="item.fileName&&text!=$t('上传')">
               {{ item.fileName.substring(item.fileName.length, item.fileName.length - 20) }} 
            </view>
            <view class="text"  @click="downLoadFile(item.url)" v-else>
				 <block v-if="text!=$t('上传') && item.url!='https://gluz-oss.oss-cn-beijing.aliyuncs.com'">
					{{ item.url.substring(item.url.length, item.url.length - 20) }}
				</block> 
				<!-- <block v-if="text!=$t('上传') && item.orderInfo.goods_list">
					{{ item.orderInfo.goods_list.substring(item.orderInfo.goods_list.length, item.orderInfo.goods_list.length - 20) }}
				</block>
				<block v-if="text!=$t('上传') && item.orderJoin.goods_list">
					{{ item.orderJoin.goods_list.substring(item.orderJoin.goods_list.length, item.orderJoin.goods_list.length - 20) }}
				</block> -->
            </view>
			<block v-if="text!=$t('上传') && postht!=1">
				<view class="delete" @click="deleteUploadList(index)">X</view>
			</block>
          </view>
        </view>
		
		<block v-if="text==this.$t('上传')">
			<view v-if="plat!='app'" class="addFiles" @click="chooseFiles" :class="color?'white':''">{{ text }}</view>
			<view v-if="plat=='app'"><upload @change="upload"></upload></view>
		</block>
		<block v-else-if="text==this.$t('重新上传')">
			<view v-if="plat!='app'" class="addFiles" @click="chooseFiles" :class="color?'white':''">{{ text }}</view>
			<view v-if="plat=='app'"><upload @change="upload"></upload></view>
		</block>
		
      
	  </view>
    </u-form-item>
  </view>
</template>
<script>
import {HTTP_REQUEST_URL, FILE_MAX_SIZE, FILE_MAX_COUNT} from '@/config/app';
import upload from "@/components/buildForm/upload.vue";
export default {
  components:{
	 upload 
  },
  props: {
    item: {
      type: [Object,null],
      default: {},
      required: true
    },
	text:{
		type:String,
		default:'上传',
	},
	color:{
		type:String,
		default:'',
	},
	showDataList:{
		type:[Array,Object,null],
		default:[]
	},
	postht:{
		type:[String,Number],
		default:'',
	},
  },
  watch: {
  	showDataList: {
  		handler(culVal) {
  			
  		},
  		immediate: true,
  		deep:true,
  	}
  },
  data() {
    return {
      uploadDataList: [],
      action: HTTP_REQUEST_URL + '/common/upload',
      imageMaxSize: FILE_MAX_SIZE,
      imageMaxCount: FILE_MAX_COUNT,
      width: 150,
      height: 150,
      autoUpload: true,
      showUploadList: true,
      delBgColor: '#fa3534',
      delColor: '#ffffff',
      uploadText: this.districts(this.$t('选择文件')),
      limitType: ['doc', 'xls', 'ppt', 'pdf', 'docx', 'xlsx', 'pptx'],
      filesLoading: false,
      plat:uni.getStorageSync('plat')
    };
  },
  mounted() {	
    this.filesLoading = true
  },
  methods: {
	  //下载文件
	  downLoadFile(url) {
	  	const that = this
	  	uni.showLoading({
	  		title:"download...",
	  		mask:true
	  	})
	  	console.log('下载链接', url)
	  	var downloadTask = uni.downloadFile({
	  		url: url,
	  		success(res) {
	  			uni.hideLoading()
	  			console.log('tempFilePath', res.tempFilePath)
	  			const tempFilePath = res.tempFilePath
	  			uni.openDocument({
	  				filePath: tempFilePath,
	  				showMenu: true,
	  				success: function(file) {
	  					console.log('file-success', file);
	  				}
	  			});
	  		},
	  	})
	  	downloadTask.onProgressUpdate(({progress,totalBytesWritten,totalBytesExpectedToWrite}) => {
	  		if(progress === 100){
	  			downloadTask.offProgressUpdate();
	  		}
	  	})
	  },
    districts(val) {
      return val.length > 6 ? val.slice(0, 6) + "..." : val
    },
    onSuccess(data, index, lists, name) {// 上传成功
      this.setFromData(lists)
    },
    onRemove(index, lists, name) {
      // console.log('remove', lists)
      this.setFromData(lists)
    },
    setFromData(lists) {
      let formData = [];
      if (lists.length > 0) {
        for (let i = 0; i < lists.length; i++) {
          if (lists[i].response) {
            let temp = {
              url: lists[i].response.data.url
            }
            formData.push(temp)
          } else if (lists[i].url) {
            let temp = {
              url: lists[i].url
            }
            formData.push(temp)
          }
        }
      } else {
        formData = []
      }
      // console.log('formData', formData)
      this.$emit('change', 'upload', formData)
    },
    chooseFiles() {
      const that = this
      // #ifdef MP-WEIXIN
      uni.chooseMessageFile({
        count: 6,
        type: 'file',
        extension: that.limitType,
        success: function (res) {
          // console.log('chooseMessageFile', res)
          const tempFilePaths = res.tempFiles
          const tempFiles = res.tempFiles
          for (let i = 0; i < tempFilePaths.length; i++) {
            that.uploadFile(tempFilePaths[i].path, tempFiles[i])
          }
        }
      });
      // #endif
      // #ifdef H5
      uni.chooseFile({
        count: 6,
        extension: that.limitType,
        success: function (res) {
          const tempFilePaths = res.tempFilePaths
          const tempFiles = res.tempFiles
          for (let i = 0; i < tempFilePaths.length; i++) {
            that.uploadFile(tempFilePaths[i], tempFiles[i])
          }
        }
      });
      // #endif
      // #ifdef APP-PLUS
      // console.log('APP')
      const lemonjkFileSelect = uni.requireNativePlugin('lemonjk-FileSelect');
      //提示：
      //1.不要忘了在 "manifest.json -> APP原生插件配置" 内添加本插件，否则云打包（离线打包）不会生效 showNativePicker
      lemonjkFileSelect.showPicker({
        //各属性配置见下方【showPicker可配置参数说明】
        pathScope: "/Download",
        mimeType: "*/*",
        utisType: "public.data",
        multi: 'yes',
        // securityPackageName: "com.android.egg",
        // securityScope: 'data'
      }, result => {
        // 返回值说明见下方【showPicker返回值说明】
        // console.log('result', result)
        // （仅安卓）当错误码为1001，即未授权文件读取权限,可以提示用户未打开读取文件权限，并跳转设置页
        if (result.code == 1001) {
          uni.showModal({
            title: that.$t("需要文件访问权限"),
            content: that.$t("您还未授权本应用读取文件。为保证您可以正常上传文件，请在权限设置页面打开文件访问权限"),
            confirmText: that.$t("去授权"),
            cancelText: that.$t("算了"),
            success(e) {
              if (e.confirm) {
                // 跳转到应用设置页
                lemonjkFileSelect.gotoSetting();
              }
            }
          })
        }
        const tempFilePaths = result.files
        for (let i = 0; i < tempFilePaths.length; i++) {
          uni.showLoading({
            title: that.$t('上传中')
          })
          // 20秒没传完，关闭提示
          setTimeout(() => {
            uni.hideLoading()
          }, 20000)
          that.uploadFile(tempFilePaths[i].filePath, tempFilePaths[i])
        }
      })
      // #endif
    },
    uploadFile(file, showFile) {
      const that = this
      if (showFile.size) {
        if (showFile.size > 52428800) {
          that.$u.toast(that.$t('上传文件过大'))
          return false
        }
      }
      if (showFile.fileSize) {
        if (showFile.fileSize > 52428800) {
          that.$u.toast(that.$t('上传文件过大'))
          return false
        }
      }
      this.showDataList.push(showFile)
      // console.log('this.showDataList', this.showDataList)
      uni.uploadFile({
        url: that.action,
        filePath: file,
        name: 'file',
        success: (uploadFileRes) => {
          // console.log('uploadFileRes', uploadFileRes)
          uni.hideLoading()
          const resData = JSON.parse(uploadFileRes.data)
          if (resData.code === 1) {
            let resUrl = {url: resData.data.url}
			that.uploadDataList=[]
            that.uploadDataList.push(resUrl)
            that.$emit('change', 'upload', that.uploadDataList)
          } else {
            that.$u.toast(resData.msg)
          }
        }
      });
    },
    deleteUploadList(index) {
      this.uploadDataList.splice(index, 1)
      this.showDataList.splice(index, 1)
      this.$emit('change', 'upload', this.uploadDataList)
    },
	upload(e,data){
		console.log(e,data)
		var that = this
		
		that.showDataList= []
		that.showDataList.push(data)
		
		that.uploadDataList= []
		that.uploadDataList.push(data)
		that.$emit('change', that.item.key, that.uploadDataList)
	}
  }
}
</script>

<style lang="scss">
.addFiles {
  color: #F79B29;
}
.white{
	color: #ffffff !important; padding: 0px !important; line-height: unset !important; border: 0px !important;	  font-size: 20rpx !important;

}
.filePreview {
  display: flex;
  flex-direction: column;

  .item {
    display: flex;
	padding-left: 3%;
    .text {
      color: #999999;
      width: 360rpx;
      overflow: hidden;
      word-wrap: break-word;
      word-break: break-all;
      white-space: normal;
	  font-size: 20rpx;
    }

    .delete {
      font-size: 20rpx;
      width: 30rpx;
      height: 30rpx;
      background-color: #fa3534;
      color: #FFFFFF;
      border-radius: 50%;
      line-height: 30rpx;
      text-align: center;
    }
  }
}
</style>
